<?php

namespace App\Models;

use App\Models\Behavior\Cat;
use App\Models\Behavior\Image;
use Illuminate\Database\Eloquent\Model;

class Behavior extends Model
{
    protected $table = 'love_behavior';

    const UPDATED_AT = null;

    public function cat()
    {
        return $this->belongsTo(Cat::Class);
    }

    public function img()
    {
        return $this->belongsTo(Image::Class, 'image_id');
    }

    /**
     * 根据行为分类获取行为
     *
     * @param $cat_id 行为分类id
     * @param $type   行为类型 0全部 1积极 2消极
     * @return mixed
     */
    public static function getBehaviorByCat($cat_id, $type = 0)
    {
        return static::where('cat_id', $cat_id)
            ->where('status', 1)
            ->when($type, function ($query) use ($type){
                return $query->where('type', $type);
            })
            ->leftJoin('love_behavior_images as b', 'b.id', 'love_behavior.image_id')
            ->select([
                'love_behavior.id','love_behavior.name','love_behavior.type','love_behavior.score',
                'love_behavior.created_at','love_behavior.image_id','b.url as image_url'
            ])
            ->get();
    }

    public static function getBehaviors()
    {
        return static::where('status', 1)
            ->leftJoin('love_behavior_images as b', 'b.id', 'love_behavior.image_id')
            ->select([
                'love_behavior.id','love_behavior.name','love_behavior.type','love_behavior.cat_id','love_behavior.score',
                'love_behavior.created_at','love_behavior.image_id','b.url as image_url'
            ])
            ->get();
    }

}
